package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.common.R;
import org.example.interceptor.UserHolder;
import org.example.mapper.WmNewsMapper;
import org.example.pojo.entity.ApCollect;
import org.example.mapper.ApCollectMapper;
import org.example.pojo.entity.WmNews;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.service.IApCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-02-04
 */
@Service
public class ApCollectServiceImpl extends ServiceImpl<ApCollectMapper, ApCollect> implements IApCollectService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Override
    public Long collect(String articleId) {
        //判断用户是否收藏
        QueryWrapper<ApCollect> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id", articleId);
        wrapper.eq("collect_user_id", UserHolder.getUserId());
        Long count = baseMapper.selectCount(wrapper);
        if (count > 0) {
            return count;
        }
        ApCollect apCollect = new ApCollect();
        apCollect.setCollectUserId(UserHolder.get().getId());
        apCollect.setArticleId(Integer.parseInt(articleId));
        apCollect.setCreateTime(LocalDateTime.now());
        baseMapper.insert(apCollect);
        return baseMapper.selectCount(new QueryWrapper<ApCollect>().eq("article_id", Integer.parseInt(articleId)));
    }

    @Override
    public Long uncollect(String articleId) {
        QueryWrapper<ApCollect> wrapper = new QueryWrapper();
        wrapper.eq("article_id", Integer.parseInt(articleId));
        wrapper.eq("collect_user_id", UserHolder.get().getId());
        baseMapper.delete(wrapper);
        return baseMapper.selectCount(new QueryWrapper<ApCollect>().eq("article_id", Integer.parseInt(articleId)));

    }

    @Override
    public R collectArticle() {
        List<ApCollect> collectUserId = baseMapper.selectList(new QueryWrapper<ApCollect>().eq("collect_user_id", UserHolder.get().getId()));
        //获取文章id
        List<Integer> articleIds = collectUserId.stream().map(ApCollect::getArticleId).collect(Collectors.toList());
        List<WmNews> wmNews = wmNewsMapper.selectBatchIds(articleIds);
        return R.ok(wmNews);
    }


}
